package com.kujawnode.config.handler;

import com.kujawnode.constant.Constants;
import com.kujawnode.model.TUser;
import com.kujawnode.result.R;
import com.kujawnode.service.RedisService;
import com.kujawnode.utils.JSONUtils;
import com.kujawnode.utils.JWTUtils;
import com.kujawnode.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Author kujaw
 * @Date 2025/7/9 14:40
 * @注释
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication)
            throws IOException, ServletException {
        // 获取用户信息
        TUser tUser = (TUser) authentication.getPrincipal();
        //1.生成jwt
        String userJSON = JSONUtils.toJSON(tUser);
        String jwt = JWTUtils.createJWT(userJSON);

        //2.写入redis
        redisService.setValue(Constants.REDIS_JWT_KEY+tUser.getId(),jwt);

        //3.设置过期时间(选择了记住我，过期时间是7天，否则30min)
        String rememberMe = request.getParameter("rememberMe");
        if(Boolean.parseBoolean(rememberMe)){
            redisService.setExpire(
                    Constants.REDIS_JWT_KEY+tUser.getId(),
                    Constants.EXPIRE_TIME,
                    TimeUnit.SECONDS
            );
        }else{
            redisService.setExpire(
                    Constants.REDIS_JWT_KEY+tUser.getId(),
                    Constants.DEFAULT,
                    TimeUnit.SECONDS
            );
        }

        //登录成功的统一结果
        R result = R.OK(jwt);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把R以JSON形式返回给前端
        ResponseUtils.write(response,resultJSON);
    }
}
